package com.jjw.service;

import com.jjw.pojo.CVDNumbers;
import com.jjw.pojo.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoronaVirusDataService implements InitializingBean {

    //爬取数据的地址
    public static final String CORONA_VIRUS_DATA_URL="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    //爬取数据后封装成的bean
    private final List<RegionStats> regionStatsList=new ArrayList<>();
    public List<RegionStats> getRegionStats(){
        return regionStatsList;
    }
    private final List<CVDNumbers> cvdNumbersList=new ArrayList<>();
    public List<CVDNumbers> getCvdNumbersList(){return cvdNumbersList;}

    @Scheduled(cron = "${jjw.Schedules.updateVirusDataCron}")
    public void fetchCoronaVirusData() throws IOException {
        //爬取csv文件,建立请求体
        RequestEntity<Void> requestEntity=RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();

        ResponseEntity<Resource> exchange=new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body=exchange.getBody();
        InputStream inputStream=body.getInputStream();
        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
        Reader in =new BufferedReader(inputStreamReader);
        Iterable<CSVRecord> records= CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        for(CSVRecord record:records){


                    RegionStats regionStats=new RegionStats();
                    regionStats.setState(record.get("Province/State"));
                    regionStats.setCountry(record.get("Country/Region"));
                    int case1=Integer.parseInt(record.get(record.size()-1));    //最后一个数据
                    int case2=Integer.parseInt(record.get(record.size()-2));   //倒数第二个数据
                    regionStats.setLatestTotalCases(case1);
                    regionStats.setDiffFromPrevDay(case1-case2);
                    regionStatsList.add(regionStats);


        }
    }



    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
